package com.jame.context;

import com.jame.aop.AopResult;
import com.jame.aop.ExecuteClassParticulars;
import com.jame.aop.ProxyFactory;
import com.jame.util.StringUtil;
import org.apache.log4j.Logger;

import java.util.*;

/**
 * @author : Jame
 * @date : 2021-07-01 15:54
 * 用于增强bean的类
 **/
public class BeanAop {
    private static BeanAop beanAop = new BeanAop();

    private BeanAop() {
    }

    public static BeanAop getBeanAop() {
        return beanAop;
    }

    private static Logger logger = Logger.getLogger(BeanContainer.class);

    private final Map<String, AopResult> aopResultMap = new HashMap<>();

    private final ProxyFactory proxyFactory = new ProxyFactory();

    /**
     * 解析需要增强的方法
     *
     * @param list
     * @return 需要进行增强的类全限定名或包名
     */
    public List<String> getExecuteAop(List<AopResult> list) {
        List<String> pathNames = new ArrayList<>();
        for (AopResult aopResult : list) {
            ExecuteClassParticulars particulars = StringUtil.analysis(aopResult);
            if (particulars == null) {
                logger.error("检查表达式");
            }
            aopResult.setExecuteClassParticulars(particulars);
            pathNames.add(aopResult.getValue() + aopResult.getAnnotationType().name());
            aopResultMap.put(aopResult.getValue() + aopResult.getAnnotationType().name(), aopResult);
        }
        return pathNames;
    }


    /**
     * 增强方法
     *
     * @param o
     * @return
     */
    public Object enhance(Object o, List<String> value) {
        List<AopResult> aopResultList = new ArrayList<>();
        for (String s : value) {
            AopResult aopResult = aopResultMap.get(s);
            if (aopResult != null) {
                aopResultList.add(aopResult);
            }
        }
        o = aopResultList.size() == 0 ? o : proxyFactory.getProxy(o.getClass(), aopResultList);
        return o;
    }


}
